`
This script assigns the first positional argument to the variable
TARGET. Notice, also, that the argument ${0} is assigned to the
SCRIPT_NAME variable. This argument contains the script’s name
(in this case, ping_with_arguments.sh).
To run this script, use the following commands:
$ chmod u+x ping_with_arguments.sh
$./ping_with_arguments.sh nostarch.com
Running the script ping_with_arguments.sh...
Pinging the target nostarch.com...
PING nostarch.com (104.20.120.46) 56(84) bytes of data.
64 bytes from 104.20.120.46 (104.20.120.46): icmp_seq=1 ttl=57 time=6.89 ms
64 bytes from 104.20.120.46 (104.20.120.46): icmp_seq=2 ttl=57 time=4.16 ms
--snip--
Listing 1-18
Passing arguments to a script
This script will perform a ping command against the domain
nostarch.com passed to it on the command line. The value was
assigned to the $1 variable; if we passed another argument, it would
get assigned to the second variable, $2. Use CTRL+C to exit this
script, as ping may run indefinitely on some operating systems.
This script is available at https://github.com/dolevf/Black-Hat-
Bash/blob/master/ch01/ping_with_arguments.sh.
What if you wanted to access all arguments? You can do so
using the variable $@. Also, using $#, you can get the total number
of arguments passed. The following script demonstrates how this
works:
#!/bin/bash
echo "The arguments are: $@"
echo "The total number of arguments are: $#"
Save this script to a file named show_args.sh and run it as
follows:
$ chmod u+x show_args.sh
$ ./show_args.sh "hello" "world"
The arguments are: hello world
The total number of arguments are: 2
Table 1-7 summarizes the variables related to positional
arguments.
Black Hat Bash (Early Access) © 2023 by Dolev Farhi and Nick Aleks